package com.haixiaoke.saas.workOrder.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.config.sms.SmsConfig;
import com.haixiaoke.saas.common.constant.WorkOrderConstants;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.sms.SmsUtils;
import com.haixiaoke.saas.lock.service.IHouseLockService;
import com.haixiaoke.saas.workOrder.domain.WorkOrderPwdRecord;
import com.haixiaoke.saas.workOrder.mapper.WorkOrderPwdRecordMapper;
import com.haixiaoke.saas.workOrder.service.IWorkOrderPwdRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 工单临时密码申请记录Service业务层处理
 *
 * @author qixi
 * @date 2024-10-10
 */
@Service
@Slf4j
public class WorkOrderPwdRecordServiceImpl implements IWorkOrderPwdRecordService {
    @Autowired
    private WorkOrderPwdRecordMapper workOrderPwdRecordMapper;

    @Autowired
    private IHouseLockService houseLockService;
    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private SmsConfig smsConfig;

    /**
     * 查询工单临时密码申请记录
     *
     * @param recordId 工单临时密码申请记录主键
     * @return 工单临时密码申请记录
     */
    @Override
    public WorkOrderPwdRecord selectWorkOrderPwdRecordByRecordId(Long recordId) {
        return workOrderPwdRecordMapper.selectWorkOrderPwdRecordByRecordId(recordId);
    }

    /**
     * 查询工单临时密码申请记录列表
     *
     * @param workOrderPwdRecord 工单临时密码申请记录
     * @return 工单临时密码申请记录
     */
    @Override
    public List<WorkOrderPwdRecord> selectWorkOrderPwdRecordList(WorkOrderPwdRecord workOrderPwdRecord) {
        return workOrderPwdRecordMapper.selectWorkOrderPwdRecordList(workOrderPwdRecord);
    }

    /**
     * 新增工单临时密码申请记录
     *
     * @param workOrderPwdRecord 工单临时密码申请记录
     * @return 结果
     */
    @Override
    public int insertWorkOrderPwdRecord(WorkOrderPwdRecord workOrderPwdRecord) {
        workOrderPwdRecord.setCreateTime(DateUtils.getNowDate());
        return workOrderPwdRecordMapper.insertWorkOrderPwdRecord(workOrderPwdRecord);
    }

    /**
     * 修改工单临时密码申请记录
     *
     * @param workOrderPwdRecord 工单临时密码申请记录
     * @return 结果
     */
    @Override
    public int updateWorkOrderPwdRecord(WorkOrderPwdRecord workOrderPwdRecord) {
        workOrderPwdRecord.setUpdateTime(DateUtils.getNowDate());
        return workOrderPwdRecordMapper.updateWorkOrderPwdRecord(workOrderPwdRecord);
    }

    /**
     * 批量删除工单临时密码申请记录
     *
     * @param recordIds 需要删除的工单临时密码申请记录主键
     * @return 结果
     */
    @Override
    public int deleteWorkOrderPwdRecordByRecordIds(Long[] recordIds) {
        return workOrderPwdRecordMapper.deleteWorkOrderPwdRecordByRecordIds(recordIds);
    }

    /**
     * 删除工单临时密码申请记录信息
     *
     * @param recordId 工单临时密码申请记录主键
     * @return 结果
     */
    @Override
    public int deleteWorkOrderPwdRecordByRecordId(Long recordId) {
        return workOrderPwdRecordMapper.deleteWorkOrderPwdRecordByRecordId(recordId);
    }

    @Override
    public String selectWorkOrderPwdApplyStatusByWorkOrderId(String workOrderId) {
        List<WorkOrderPwdRecord> workOrderPwdRecords = workOrderPwdRecordMapper.selectWorkOrderPwdRecordByWorkOrderId(workOrderId);
        if (CollectionUtil.isEmpty(workOrderPwdRecords)) {
            return WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_APPLY_STATUS_NOT_APPLY;
        }

        List<WorkOrderPwdRecord> collect = workOrderPwdRecords.stream().filter(workOrderPwdRecord -> ObjectUtil.equal(workOrderPwdRecord.getPwdAuditState(), WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_AUDIT_STATUS_REFUSE)).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(collect)) {
            return WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_APPLY_STATUS_REFUSE;
        }

        // 校验是否超过两小时
        List<WorkOrderPwdRecord> records = workOrderPwdRecords.stream().filter(workOrderPwdRecord -> ObjectUtil.equal(workOrderPwdRecord.getPwdAuditState(), WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_AUDIT_STATUS_AGREE))
                .sorted(Comparator.comparing(WorkOrderPwdRecord::getUpdateTime, Comparator.nullsFirst(Comparator.naturalOrder()))).collect(Collectors.toList());
        ;
        WorkOrderPwdRecord workOrderPwdRecord = records.get(0);
        if (DateUtil.offset(workOrderPwdRecord.getUpdateTime(), DateField.MINUTE, 120).compareTo(DateUtils.getNowDate()) < 0) {
            return WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_APPLY_STATUS_APPLY;
        } else {
            return WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_APPLY_STATUS_NOT_APPLY;
        }
    }

    @Override
    @Transactional
    public int auditWorkOrderPwdRecord(WorkOrderPwdRecord workOrderPwdRecord) {
        Long workOrderId = workOrderPwdRecord.getRecordId();
        if (ObjectUtil.isEmpty(workOrderId)) {
            throw new ServiceException("工单临时密码申请记录id不能为空");
        }
        Date nowDate = DateUtils.getNowDate();
        WorkOrderPwdRecord workOrderPwdRecord1 = workOrderPwdRecordMapper.selectWorkOrderPwdRecordByRecordId(workOrderId);
        if (ObjectUtil.isEmpty(workOrderPwdRecord1)) {
            throw new ServiceException("工单临时密码申请记录不存在");
        }

        if (workOrderPwdRecord.getPwdAuditState().equals(WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_AUDIT_STATUS_AGREE)) {
            workOrderPwdRecord1.setPwdStartTime(nowDate);
            workOrderPwdRecord1.setPwdEndTime(DateUtil.offset(nowDate, DateField.MINUTE, 120));
            workOrderPwdRecord1.setPwdAuditState(WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_AUDIT_STATUS_AGREE);

            // 发送临时密码
            houseLockService.workOrderAuthPwd(workOrderPwdRecord1);
            workOrderPwdRecord1.setRemark("人工审核通过");

        } else if (workOrderPwdRecord.getPwdAuditState().equals(WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_AUDIT_STATUS_REFUSE)) {
            if (StrUtil.isBlank(workOrderPwdRecord.getRemark())) {
                throw new ServiceException("请填写拒绝原因");
            }
            workOrderPwdRecord1.setRemark(workOrderPwdRecord.getRemark());
            workOrderPwdRecord1.setPwdAuditState(WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_AUDIT_STATUS_REFUSE);

            boolean smsWithData = smsUtils.sendTemplateSmsWithData(workOrderPwdRecord.getReqPhone(), smsConfig.getWorkOrderPwdApplyConsentCode(), new String[]{
                    workOrderPwdRecord.getPremisesAddress(), "看房", workOrderPwdRecord.getRemark()});
            if (!smsWithData) {
                log.error("短信发送失败");
            }
        }
        workOrderPwdRecord1.setUpdateTime(nowDate);
        workOrderPwdRecord1.setUpdateBy(workOrderPwdRecord.getUpdateBy());
        return workOrderPwdRecordMapper.updateWorkOrderPwdRecord(workOrderPwdRecord1);
    }

    @Override
    public Map<String, Object> selectWorkOrderPwdRecordCountPwdAuditState(WorkOrderPwdRecord workOrderPwdRecord) {
        List<Map<String, Object>> list = workOrderPwdRecordMapper.selectWorkOrderPwdRecordCountPwdAuditState(workOrderPwdRecord);
        Map<String, Object> map = new HashMap<>();
        map.put(WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_APPLY_STATUS_NOT_APPLY, 0);
        map.put(WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_APPLY_STATUS_APPLY, 0);
        map.put(WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_APPLY_STATUS_REFUSE, 0);

        //密码码状态: (0待审核 1同意 2拒绝)
        if (!CollectionUtil.isEmpty(list)){
            list.forEach(item -> {
                String o = Convert.toStr(item.get("pwdAuditState"));
                if (StrUtil.isNotBlank(o)){
                    map.put(o, item.get("count"));
                }
            });
        }
        return map;
    }
}
